package com.example.yurpceasy.fault.retry;

import com.example.yurpceasy.model.RpcResponse;
import com.github.rholder.retry.*;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * 固定时间间隔的重试策略
 */
@Slf4j
public class FixedIntervalRetryStrategy implements RetryStrategy {
    @Override
    public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception {
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfExceptionOfType(Exception.class) // 出现这种异常时重试
                .withWaitStrategy(WaitStrategies.fixedWait(3L, TimeUnit.SECONDS)) // 重试等待策略是 3s 重试一次
                .withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 重试停止策略是 超过最大重试策略3次后就不重试了
                .withRetryListener(new RetryListener() { // 重试监听
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        if (attempt.hasException()){
                            log.info("重试次数 {} ", attempt.getAttemptNumber());
                        }
                    }
                }).build();
        return retryer.call(callable);
    }
}
